//
//  UserManager.m
//  MiAiApp
//
//  Created by 徐阳 on 2017/5/22.
//  Copyright © 2017年 徐阳. All rights reserved.
//

#import "UserManager.h"


@implementation UserManager

SINGLETON_FOR_CLASS(UserManager);

-(instancetype)init{
    self = [super init];
    if (self) {
        //被踢下线
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onKick)
                                                     name:KNotificationOnKick
                                                   object:nil];
    }
    return self;
}

#pragma mark ————— 三方登录 —————
-(void)login:(UserLoginType )loginType completion:(loginBlock)completion{
    [self login:loginType params:nil completion:completion];
}

#pragma mark ————— 带参数登录 —————
-(void)login:(UserLoginType )loginType params:(NSDictionary *)params completion:(loginBlock)completion{
   
}

#pragma mark ————— 手动登录到服务器 —————
-(void)loginToServer:(NSDictionary *)params completion:(loginBlock)completion{
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KLoginUrl parameters:params success:^(id  _Nonnull responseObject) {
        completion(YES, @"登录成功");
    } failure:^(NSError * _Nonnull error) {
        completion(NO, @"登录失败");
    }];
}

#pragma mark ————— 自动登录到服务器 —————
-(void)autoLoginToServer:(loginBlock)completion{
 
}

#pragma mark ————— 登录成功处理 —————
-(void)LoginSuccess:(id )responseObject completion:(loginBlock)completion{
    if (ValidDict(responseObject)) {
        if (ValidDict(responseObject[@"data"])) {
            NSDictionary *data = responseObject[@"data"];
            if (ValidStr(data[@"imId"]) && ValidStr(data[@"imPass"])) {
                //登录IM
//                [[IMManager sharedIMManager] IMLogin:data[@"imId"] IMPwd:data[@"imPass"] completion:^(BOOL success, NSString *des) {
//                    [MBProgressHUD hideHUD];
//                    if (success) {
//                        self.curUserInfo = [UserInfo modelWithDictionary:data];
//                        [self saveUserInfo];
//                        self.isLogined = YES;
//                        if (completion) {
//                            completion(YES,nil);
//                        }
//                        KPostNotification(KNotificationLoginStateChange, @YES);
//                    }else{
//                        if (completion) {
//                            completion(NO,@"IM登录失败");
//                        }
//                        KPostNotification(KNotificationLoginStateChange, @NO);
//                    }
//                }];
            }else{
                if (completion) {
                    completion(NO,@"登录返回数据异常");
                }
                KPostNotification(KNotificationLoginStateChange, @NO);
            }
            
        }
    }else{
        if (completion) {
            completion(NO,@"登录返回数据异常");
        }
        KPostNotification(KNotificationLoginStateChange, @NO);
    }
    
}

#pragma mark ————— 储存用户信息 —————
- (UserInfo *)saveUserInfo:(UserInfo *)userinfo{
    if (userinfo) {
        YYCache *cache = [[YYCache alloc] initWithName:KUserCacheName];
        NSDictionary *dic = [userinfo yy_modelToJSONObject];
        [cache setObject:dic forKey:KUserModelCache];
        
        [self getUserInfo];
    }
    return userinfo;
}

#pragma mark ————— 加载缓存的用户信息 —————
// TODO: 在读取操作数量过大 会导致缓存丢失  注意！！！ 一般操作应该使用curUserInfo
- (UserInfo *)getUserInfo {
    NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

    NSString *cachesDir = [paths1 objectAtIndex:0];

    NSLog(@"%@",cachesDir);
    
    
    YYCache *cache = [[YYCache alloc] initWithName:KUserCacheName];
    NSDictionary * userDic = (NSDictionary *)[cache objectForKey:KUserModelCache];
    if (userDic) {
        self.curUserInfo = [UserInfo yy_modelWithJSON:userDic];
        return self.curUserInfo;
    }
    return nil;
}

#pragma mark ————— 被踢下线 —————
-(void)onKick{
    [self logout:nil];
}

#pragma mark ————— 退出登录 —————
- (void)logout:(void (^)(BOOL, NSString *))completion{
    [self logoutRequest:^(BOOL success, NSString *des) {
        dispatch_sync_on_main_queue(^{
            if (completion) {
                completion(YES, nil);
            }
            HELoginViewController *vc = [[HELoginViewController alloc] init];
            kApplication.keyWindow.rootViewController = vc;
        });
    }];
}

- (void)logoutProcss:(void (^)(BOOL, NSString *))completion {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];

//    [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationLogout object:nil];//被踢下线通知用户退出直播间
    
//    [[IMManager sharedIMManager] IMLogout];
    
    // 关闭聊天室
    [[JPSuspensionEntrance sharedInstance] removeSuspensionView];
    
    // 关闭socket
    [[HESocketManager sharedManager] close];
    
    self.curUserInfo = nil;
    self.isLogined = NO;
     
    [[UserManager sharedUserManager] removeToken];
    
    [UserManager sharedUserManager].archiveInfo = nil;
     
//    //移除缓存
    YYCache *cache = [[YYCache alloc] initWithName:KUserCacheName];
    [cache removeAllObjectsWithBlock:^{
        if (completion) {
            completion(YES, nil);
        }
    }];
     
    KPostNotification(KNotificationLoginStateChange, @NO);
}

- (void)logoutRequest:(void (^)(BOOL, NSString *))completion {
    NSString *token = [[UserManager sharedUserManager] getToken];

    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:@"logout" forKey:@"method"];
    [params setValue:token forKey:@"token"];
    
    [self logoutProcss:^(BOOL success, NSString *des) {
        if (completion) {
            completion(YES, nil);
        }
    }];
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KLoginUrl parameters:params token:nil success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        
        if (!response.success) {
            return;
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}


- (void)saveToken:(NSString *)token forKey:(NSString *)key {
    [HEKeyChain setObject:token forKey:key];
}

- (NSString *)getToken {
    if (self.curUserInfo == nil) {
        [[UserManager sharedUserManager] getUserInfo];
    }
    if (self.curUserInfo == nil) {
        return nil;
    }
    return (NSString *)[HEKeyChain objectForKey:self.curUserInfo.username];
}

- (void)removeToken {
    if (self.curUserInfo == nil) {
        [[UserManager sharedUserManager] getUserInfo];
    }
    if (self.curUserInfo != nil) {
        [HEKeyChain removeObjectForKey:self.curUserInfo.username];
    }
}


#pragma mark -  AI
- (void)saveAIDataWithFiter: (NSArray <GDFiterCellModel *> *)fiters forms: (NSArray <GDFormModel *> *)forms {
    
    NSMutableArray <HEAIMsgModel *> *ms = @[].mutableCopy;
    
    int j = 0;
    for (NSInteger i = (forms.count - 1); i >= 0; i--) {
        
        if (j == 200) {
            break;
        }
        GDFormModel *model = forms[i];
        [ms addObject: model.zx_model];
        j++;
    }
//    for (GDFormModel *model in forms) {
//        if (i == 200) {
//            break;
//        }
//        [ms addObject: model.zx_model];
//        i++;
//    }
    
    ms = ms.reverseObjectEnumerator.allObjects;
    
    HEAIData *data = [HEAIData new];
    data.fiterArrJSONString = @"";
    data.formArrJSONString = [ms yy_modelToJSONString];
    
    UserInfo *user = [[UserManager sharedUserManager] getUserInfo];
    NSString *aiDataKey = [NSString stringWithFormat:@"%@:%@",KUserAIDataCache, user.id];
    
    YYCache *cache = [[YYCache alloc] initWithName:aiDataKey];
    NSDictionary *dic = [data yy_modelToJSONObject];
    [cache setObject:dic forKey: KUserAIDataCache];
}
- (void)getAIData:(UIViewController *)vc {
    NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

    NSString *cachesDir = [paths1 objectAtIndex:0];

    NSLog(@"%@",cachesDir);
     
    UserInfo *user = [[UserManager sharedUserManager] getUserInfo];
    NSString *aiDataKey = [NSString stringWithFormat:@"%@:%@",KUserAIDataCache, user.id];
    YYCache *cache = [[YYCache alloc]initWithName:aiDataKey];
    NSDictionary * userDic = (NSDictionary *)[cache objectForKey: KUserAIDataCache];
    if (userDic) {
        
        HEAIData *data = [HEAIData mj_objectWithKeyValues:userDic];

        NSArray *allMsgStr = [DYTools getContainersObjectFromJsonString: data.formArrJSONString];
        NSArray <HEAIMsgModel *> *msgArr = [HEAIMsgModel mj_objectArrayWithKeyValuesArray: data.formArrJSONString];

        NSMutableArray <GDFormModel *> *forms = @[].mutableCopy;
        NSMutableArray <GDFiterCellModel *> *fiterArr = @[].mutableCopy;

        for (HEAIMsgModel *item in msgArr) {
            
            // 全部
//            item.isFinish = YES;
            
            GDFiterCellModel *diagModel = [GDFiterCellModel new];
            diagModel.cellKlass = [item getCellClass];
            [fiterArr addObject: diagModel];

            GDFormModel *fmodel = [GDFormModel new];
            fmodel.zx_model = item;
            fmodel.zx_model.isFinish = YES;
            fmodel.proxyVC = vc;
            [forms addObject:fmodel];
        }
 
        self.aiFiterCellArr = fiterArr;
        self.aiDatasourceArr = forms;
    }
 
}

/** 切换main*/
- (void)reloadMain {
    // 关闭聊天室
    [[HECircleChatManager sharedManager] closeAllRoom];
    
    kAppDelegate.mainTabBar = [[MainTabBarController alloc] init];
    kRootViewController = kAppDelegate.mainTabBar;
    [[HESocketManager sharedManager] connect];
}

@end
